package fish.utils
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.system.System;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	public class SystemInfoMonitor extends Sprite
	{
		private var _container:Sprite;
		private var _data:Array;
		private var _lastCheckTime:Number = 0;
		private var _fpss:Number = 0;
		private var _fps:Array;
		private var _text:TextField;
		
		public function SystemInfoMonitor()
		{
			super();
			
			_data = new Array();
			_fps = new Array();
			_container = new Sprite();
			with(_container.graphics) {
				beginFill(0x000000, 0.5);
				drawRect(0, 0, 80, 60);
				endFill();
			}
			addChild(_container);
			
			_text = new TextField();
			_text.x = 0;
			_text.y = 60;
			_text.width = 80;
			addChild(_text);
			
			addEventListener(Event.ENTER_FRAME, onTimerHandler);
		}
		
		protected function onTimerHandler(event:Event):void
		{
			var time:uint = flash.utils.getTimer();
			if((time - 500) > _lastCheckTime) {
				var memory:Number = Number(Number(System.totalMemory / 1024 / 1024).toFixed(2));
				var currentFPS:Number = Number(_fpss * 2);

				_data.push(memory);
				_fps.push(currentFPS);
				if(_data.length > 40) {
					_data.shift();
				}
				if(_fps.length > 40) {
					_fps.shift();
				}
				_fpss = 0;
				
				_text.text = "M" + memory + " F" + currentFPS;
				
				_container.graphics.moveTo(-1, 60);
				_container.graphics.lineStyle(1, 0xd90000);
				for(var i:Number = 0;i<_data.length;i++) {
					with(_container.graphics) {
						lineTo(i*2, _data[i] / 100 * 60);
					}
				}
				_container.graphics.moveTo(-1, 60);
				_container.graphics.lineStyle(1, 0x0000d9);
				for(i = 0;i<_fps.length;i++) {
					with(_container.graphics) {
						lineTo(i*2, _fps[i]);
					}
				}
				
				_lastCheckTime = time;
				
			}
			_fpss++;
		}
	}
}